﻿using CSRedis;
using Newtonsoft.Json;
using QskjBaseDataToDb.Dto;
using QskjLibrary;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QskjBaseDataToDb.Service
{
    public class ZtCarDataUpdate
    {
        /// <summary>
        /// 中台出租车基础数据
        /// </summary>
        public static void UpdateCarData()
        {
            string? token = string.Empty;
            try
            {
                //出租数据
                //string dtStrPre = DateTime.Now.AddDays(-5).ToString("yyyyMMdd");
                //string sqlPre = $@"drop table if exists qskjrecord.B_TaxiZT{dtStrPre}";
                //MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sqlPre);
                string dtStr = DateTime.Now.ToString("yyyyMMdd");
                //if (DateTime.Now.Hour < 7)
                {
                    string exists = $@"SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'qskjrecord' AND TABLE_NAME = 'B_TaxiZT{dtStr}';";
                    object resExi = MySqlHelper.ExecuteScalar(CommandType.Text, exists);
                    if (resExi == null || resExi == DBNull.Value)
                    {
                        string sql = $@"create table IF NOT EXISTS qskjrecord.B_TaxiZT{dtStr}
                        (
                           id                   bigint not null auto_increment,
                           code            varchar(50),
                           car_color            varchar(50),
                           car_numbers          varchar(50),
                           dep                  varchar(50),
                           supply_name          varchar(50),
                           activation_date      varchar(50),
                           car_assets_name_name varchar(50), 
                           car_num         varchar(50), 
                           accountname         varchar(50), 
                           business_unit         varchar(50), 
                           shortname         varchar(50), 
                           car_status_name      varchar(50) comment '车辆状态',
                           primary key (id)
                        );";
                        MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sql);
                    }
                    string exists1 = $@"SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'qskjrecord' AND TABLE_NAME = 'B_BusZT{dtStr}';";
                    object resExi1 = MySqlHelper.ExecuteScalar(CommandType.Text, exists1);
                    if (resExi1 == null || resExi1 == DBNull.Value)
                    {
                        //string sqlPreBus = $@"drop table if exists qskjrecord.B_BusZT{dtStrPre}";
                        //MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sqlPreBus);
                        string sqlBus = $@"create table IF NOT EXISTS qskjrecord.B_BusZT{dtStr}
                        (
                           id                   bigint not null auto_increment,
                           supply_name              varchar(50),
                           code         varchar(50),
                           activation_date                 varchar(500),
                           car_color                  varchar(50),
                           car_assets_name_name        varchar(50),
                           dep                  varchar(50),
                           car_numbers             varchar(50),  
                           car_num                 varchar(50),  
                           accountname         varchar(50), 
                           business_unit         varchar(50), 
                           shortname         varchar(50), 
                           car_status_name      varchar(50) comment '车辆状态',
                           odep                  varchar(50),
                           terminalkey                  varchar(50),
                           primary key (id)
                        );";
                        MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sqlBus);
                    }
                    string exists2 = $@"SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'qskjrecord' AND TABLE_NAME = 'B_OrganizationZT{dtStr}';";
                    object resExi2 = MySqlHelper.ExecuteScalar(CommandType.Text, exists2);
                    if (resExi2 == null || resExi2 == DBNull.Value)
                    {
                        //string sqlOrg = $@"drop table if exists qskjrecord.B_OrganizationZT{dtStrPre}";
                        //MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sqlOrg);
                        string sqlOrgDt = $@"create table IF NOT EXISTS qskjrecord.B_OrganizationZT{dtStr}
                        (
                           id                   bigint not null auto_increment,
                           dept_1               varchar(50),
                           deptname_1           varchar(50),
                           dept_2               varchar(50),
                           deptname_2           varchar(50),
                           dept_3               varchar(50),
                           deptname_3           varchar(50),
                           dept_4               varchar(50),
                           deptname_4           varchar(50),
                           dept_5               varchar(50),
                           deptname_5           varchar(50),
                           primary key (id)
                        );";
                        MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sqlOrgDt);
                    }
                }
                string sqlCount = $@"select count(*) from qskjrecord.B_BusZT{dtStr}";
                if (Convert.ToInt32(MySqlHelper.ExecuteScalar(CommandType.Text, sqlCount)) > 0)
                {
                    Console.WriteLine(DateTime.Now + "中台《出租车》数据已读取成功");
                    return;
                }
                //读取中台出租车数据
                if (string.IsNullOrEmpty(token))
                {
                    try
                    {
                        ZtTokenDataInfo response = JsonConvert.DeserializeObject<ZtTokenDataInfo>(HttpHelper.GetZtToken().Result);
                        if (response == null)
                        {
                            Console.WriteLine("获取token失败response为空");
                            return;
                        }
                        if (string.IsNullOrEmpty(response.data))
                        {
                            Console.WriteLine("获取token失败response.data为空");
                            return;
                        }
                        token = response.data;

                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("获取token异常：" + e);
                    }
                }
                var str = HttpHelper.GetZtCar(token).Result;
                ZtDataObj<ZtDataResInfo> obj = JsonConvert.DeserializeObject<ZtDataObj<ZtDataResInfo>>(str);
                if (obj == null || obj.data == null || string.IsNullOrEmpty(obj.data.total) || obj.data.total == "0")//当天查不到数据就把昨天的数据导入今日数据表中
                {
                    Console.WriteLine(DateTime.Now + "读取中台出租车数据失败获取前一日数据写入今日数据" + str);

                    string dtStr1 = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
                    string insertSql1 = $@"insert into qskjrecord.B_TaxiZT{dtStr}(code,car_color,car_numbers,dep,supply_name,activation_date,car_assets_name_name,car_num,accountname,business_unit,shortname)
                                        select code,car_color,car_numbers,dep,supply_name,activation_date,car_assets_name_name,car_num,accountname,business_unit,shortname from  qskjrecord.B_TaxiZT{dtStr1}";
                    MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, insertSql1);
                    string insertSql2 = $@"insert into qskjrecord.B_BusZT{dtStr}(supply_name,code,activation_date,car_color,car_assets_name_name,dep,car_numbers,car_num,accountname,business_unit,shortname)
                                        select supply_name,code,activation_date,car_color,car_assets_name_name,dep,car_numbers,car_num,accountname,business_unit,shortname from  qskjrecord.B_BusZT{dtStr1}";
                    MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, insertSql2);
                }
                foreach (var item in obj.data.dataArray)//读取到数据就写入到当日表中(出租车)
                {
                    string insertSql = $@"insert into qskjrecord.B_TaxiZT{dtStr}(code,car_color,car_numbers,dep,supply_name,activation_date,car_assets_name_name,car_num,accountname,business_unit,shortname,car_status_name)
                                        values('{item.code}','{item.car_color}','{item.car_numbers}','{item.dep}','{item.supply_name}','{item.activation_date}','{item.car_assets_name_name}','{item.car_numbers.Substring(1)}','{item.accountname}','{item.business_unit}','{item.shortname}','{item.car_status_name}')";
                    MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, insertSql);
                }
                CSRedisClient? cSRedisClient6 = RedisHelp.GetInstance6();
                //大巴数据
                //ZtDataObj<ZtBusData> objBus = JsonConvert.DeserializeObject<ZtDataObj<ZtBusData>>(str);
                foreach (var item in obj.data.dataArray)//读取到数据就写入到当日表中(大巴车)
                {
                    string odep = item.dep;
                    if (item.car_status_name == "未启运")
                    {
                        item.dep = "未启运车队";
                    }
                    string insertSql = $@"insert into qskjrecord.B_BusZT{dtStr}(supply_name,code,activation_date,car_color,car_assets_name_name,dep,car_numbers,car_num,accountname,business_unit,shortname,car_status_name,odep,terminalkey)
                                        values('{item.supply_name}','{item.code}','{item.activation_date}','{item.car_color}','{item.car_assets_name_name}','{item.dep}','{item.car_numbers}','{item.car_numbers.Substring(1)}','{item.accountname}','{item.business_unit}','{item.shortname}','{item.car_status_name}','{odep}','{item.dvr_numbers}')";
                    MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, insertSql);
                    cSRedisClient6.Set($@"isUsed:{item.car_numbers}", item.car_status_name, new TimeSpan(23, 59, 00));
                }
                {
                    //中台组织架构信息 
                    var strOrg = HttpHelper.GetZtOrg(token).Result;
                    ZtDataObj<ZtOrg> objOrg = JsonConvert.DeserializeObject<ZtDataObj<ZtOrg>>(strOrg);
                    if (objOrg == null || objOrg.data == null || string.IsNullOrEmpty(objOrg.data.total) || objOrg.data.total == "0")
                    {
                        Console.WriteLine(DateTime.Now + "读取中台组织架构数据" + str);
                        string dtStr1 = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
                        string insertSql1 = $@"insert into qskjrecord.B_OrganizationZT{dtStr}(dept_1,deptname_1,dept_2,deptname_2,dept_3,deptname_3,dept_4,deptname_4,dept_5,deptname_5)
                                        select dept_1,deptname_1,dept_2,deptname_2,dept_3,deptname_3,dept_4,deptname_4,dept_5,deptname_5 from  qskjrecord.B_OrganizationZT{dtStr1}";
                        MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, insertSql1);
                    }
                    foreach (var item in objOrg.data.dataArray)
                    {
                        string insertSql = $@"insert into qskjrecord.B_OrganizationZT{dtStr}(dept_1,deptname_1,dept_2,deptname_2,dept_3,deptname_3,dept_4,deptname_4,dept_5,deptname_5)
                                        values('{item.dept_1}','{item.deptname_1}','{item.dept_2}','{item.deptname_2}','{item.dept_3}','{item.deptname_3}','{item.dept_4}','{item.deptname_4}','{item.dept_5}','{item.deptname_5}')";
                        MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, insertSql);
                    }
                }
                //{
                //    string sqlObj = $@"select * from qskjrecord.B_BusZT{dtStr}";
                //    DataTable dtTest = MySqlHelper.GetDataTable(CommandType.Text, sqlObj);
                //    foreach (DataRow dr in dtTest.Rows)
                //    {
                //        ZtDataResInfo testM = new ZtDataResInfo();
                //        testM.supply_name = dr["supply_name"] == DBNull.Value ? "" : dr["supply_name"].ToString();
                //        testM.code = dr["code"] == DBNull.Value ? "" : dr["code"].ToString();
                //        testM.activation_date = dr["activation_date"] == DBNull.Value ? "" : dr["activation_date"].ToString();
                //        testM.car_color = dr["car_color"] == DBNull.Value ? "" : dr["car_color"].ToString();
                //        testM.car_assets_name_name = dr["car_assets_name_name"] == DBNull.Value ? "" : dr["car_assets_name_name"].ToString();
                //        testM.dep = dr["dep"] == DBNull.Value ? "" : dr["dep"].ToString();
                //        testM.car_numbers = dr["car_numbers"] == DBNull.Value ? "" : dr["car_numbers"].ToString();
                //        testM.accountname = dr["accountname"] == DBNull.Value ? "" : dr["accountname"].ToString();
                //        testM.business_unit = dr["business_unit"] == DBNull.Value ? "" : dr["business_unit"].ToString();
                //        testM.shortname = dr["shortname"] == DBNull.Value ? "" : dr["shortname"].ToString();
                //        testM.terminalkey = dr["terminalkey"] == DBNull.Value ? "" : dr["terminalkey"].ToString(); 
                //        obj.data.dataArray.Add(testM);
                //    }
                //}
                {
                    ////测试车添加到每日数据表
                    //string sqlTestBus = $@"insert into qskjrecord.B_BusZT{dtStr}(supply_name,code,activation_date,car_color,car_assets_name_name,dep,car_numbers,car_num,accountname,business_unit,shortname)
                    //                    select distinct 'cs',code,activation_date,car_color,car_assets_name_name,dep,car_numbers,car_num,accountname,business_unit,shortname from qskj.B_BusZTTest
                    //                    WHERE car_numbers NOT IN(SELECT car_numbers FROM qskjrecord.B_BusZT{dtStr}); ";
                    //MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sqlTestBus);
                    string sqlTest = $@"select distinct supply_name,code,activation_date,car_color,car_assets_name_name,dep,car_numbers,car_num,accountname,business_unit,shortname,terminalkey,zltype from qskj.B_BusZTTest
                                        WHERE car_numbers NOT IN(SELECT car_numbers FROM qskjrecord.B_BusZT{dtStr});";
                    DataTable dtTest = MySqlHelper.GetDataTable(CommandType.Text, sqlTest);
                    foreach (DataRow dr in dtTest.Rows)
                    {
                        ZtDataResInfo testM = new ZtDataResInfo();
                        testM.supply_name = dr["supply_name"] == DBNull.Value ? "" : dr["supply_name"].ToString();
                        testM.code = dr["code"] == DBNull.Value ? "" : dr["code"].ToString();
                        testM.activation_date = dr["activation_date"] == DBNull.Value ? "" : dr["activation_date"].ToString();
                        testM.car_color = dr["car_color"] == DBNull.Value ? "" : dr["car_color"].ToString();
                        testM.car_assets_name_name = dr["car_assets_name_name"] == DBNull.Value ? "" : dr["car_assets_name_name"].ToString();
                        testM.dep = dr["dep"] == DBNull.Value ? "" : dr["dep"].ToString();
                        testM.car_numbers = dr["car_numbers"] == DBNull.Value ? "" : dr["car_numbers"].ToString();
                        testM.accountname = dr["accountname"] == DBNull.Value ? "" : dr["accountname"].ToString();
                        testM.business_unit = dr["business_unit"] == DBNull.Value ? "" : dr["business_unit"].ToString();
                        testM.shortname = dr["shortname"] == DBNull.Value ? "" : dr["shortname"].ToString();
                        testM.terminalkey = dr["terminalkey"] == DBNull.Value ? "" : dr["terminalkey"].ToString();
                        testM.zltype = dr["zltype"] == DBNull.Value ? "" : dr["zltype"].ToString();
                        {
                            //测试车添加到每日数据表
                            string sqlTestBus = $@"insert into qskjrecord.B_BusZT{dtStr}(supply_name,code,activation_date,car_color,car_assets_name_name,dep,car_numbers,car_num,accountname,business_unit,shortname)
                                                    values('cs','{testM.code}','{testM.activation_date}','{testM.car_color}','{testM.car_assets_name_name}','{testM.dep}','{testM.car_numbers}','{testM.car_numbers}','{testM.accountname}','{testM.business_unit}','{testM.shortname}'); ";
                            MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sqlTestBus);
                        }
                        obj.data.dataArray.Add(testM);
                    }
                }
                #region 出租车基础数据组织架构关系处理
                try
                {
                    List<FilialeInfo> listFili = new List<FilialeInfo>();
                    #region 获取现有数据结构
                    string sqlFili = $@" select c.id,c.name,a.license_plate,a.id carid from qskj.B_Taxi a
                                         left join qskj.R_TaxiFili_Taxi b on a.id=b.taxiid
                                         left join qskj.B_Taxi_Filiale c on b.filialeid=c.id;";
                    DataTable dt = MySqlHelper.GetDataTable(CommandType.Text, sqlFili);
                    foreach (DataRow dr in dt.Rows)
                    {
                        FilialeInfo filialeInfo = new FilialeInfo();
                        filialeInfo.id = dr["id"] == DBNull.Value ? 0 : Convert.ToInt32(dr["id"]);
                        filialeInfo.name = dr["name"] == DBNull.Value ? "" : Convert.ToString(dr["name"]);
                        filialeInfo.carid = dr["carid"] == DBNull.Value ? 0 : Convert.ToInt32(dr["carid"]);
                        filialeInfo.license_plate = dr["license_plate"] == DBNull.Value ? "" : Convert.ToString(dr["license_plate"]);
                        listFili.Add(filialeInfo);
                    }
                    #endregion
                    foreach (var item in obj.data.dataArray)
                    {
                        if (item.car_assets_name_name == "上海强生出租汽车有限公司")
                        {
                            #region 车牌号车队名与现有结构一致不作处理
                            if (listFili.Exists(p => p.license_plate == item.car_numbers && p.name == item.dep))
                            {
                                continue;
                            }
                            #endregion
                            #region 车牌号车队名与现有结构不一致
                            else
                            {
                                string ztFili = item.dep;//中台数据库--当前车辆现归属车队名
                                FilialeInfo cuCar = listFili.FirstOrDefault(p => p.license_plate == item.car_numbers);//本地数据库中是否存在当前车辆
                                #region 本地数据库存在当前车辆信息
                                if (cuCar != null)
                                {
                                    try
                                    {
                                        FilialeInfo cuFili = listFili.FirstOrDefault(p => p.name == ztFili);//判断是否存在中台车队名称
                                        int filialeid = 0;
                                        #region 不存在车队名称需要添加新车队
                                        if (cuFili == null)
                                        {
                                            string inFili = $@"insert into qskj.B_Taxi_Filiale(name,code,sort,is_delete,createuser,createtime,updateuser,updatetime)values('{ztFili}','{ztFili}',1,0,'QskjBaseDataToDb',now(),'QskjBaseDataToDb',now());SELECT LAST_INSERT_ID();";
                                            object o = MySqlHelper.ExecuteScalar(CommandType.Text, inFili);
                                            filialeid = o == null ? 0 : Convert.ToInt32(o);
                                            FilialeInfo info = new FilialeInfo();
                                            info.id = filialeid;
                                            info.name = ztFili;
                                            listFili.Add(info);
                                            string InfR = $@"  insert into qskj.R_Role_Filiale(roleid,filialeId,role_type,sort,is_delete,createuser,createtime,updateuser,updatetime)
                                                    values(1,{filialeid},3,0,0,'QskjBaseDataToDb',now(),'QskjBaseDataToDb',now()),(2,{filialeid},3,0,0,'QskjBaseDataToDb',now(),'QskjBaseDataToDb',now()),(3,{filialeid},3,0,0,'QskjBaseDataToDb',now(),'QskjBaseDataToDb',now());";
                                            MySqlHelper.ExecuteNonQuery(CommandType.Text, InfR);
                                            Console.WriteLine($"不存在车队名称需要添加新车队ztFili{ztFili}");
                                        }
                                        #endregion
                                        #region 存在车队名称删除原有的车队配置
                                        else
                                        {
                                            filialeid = cuFili.id;
                                            #region 删除原有的车队配置
                                            string deFili = $@"delete from qskj.R_TaxiFili_Taxi where taxiid in(select id from qskj.B_Taxi where license_plate='{item.car_numbers}')";
                                            MySqlHelper.ExecuteNonQuery(CommandType.Text, deFili);
                                            Console.WriteLine($"删除原有的车队配置license_plate{item.car_numbers}");
                                            #endregion
                                        }
                                        #endregion
                                        #region 配置车辆车队归属信息
                                        string inRFiliCar = $@"insert into qskj.R_TaxiFili_Taxi(filialeid,taxiid,companyid,sort,is_delete,createuser,createtime,updateuser,updatetime)values({filialeid},{cuCar.carid},1,1,0,'QskjBaseDataToDb',now(),'QskjBaseDataToDb',now());";
                                        MySqlHelper.ExecuteNonQuery(CommandType.Text, inRFiliCar);
                                        Console.WriteLine($"配置车辆车队归属信息filialeid{filialeid}taxiid{cuCar.carid}");
                                        #endregion
                                        string isE = $@"select id from qskj.R_Role_Channel where role_type=3 and roleid=1 and channelid={cuFili.carid}";
                                        object isERes = MySqlHelper.ExecuteScalar(CommandType.Text, isE);
                                        if (isERes == null)
                                        {
                                            #region 配置车辆权限到固定角色
                                            {
                                                string inRrc1 = $@" INSERT INTO qskj.R_Role_Channel (roleid, channelid, role_type, sort, is_delete, createuser, createtime, updateuser, updatetime)
                                             VALUES (1, {cuFili.carid}, 3, 0, 0, 'QskjBaseDataToDb', now(), 'QskjBaseDataToDb', now());";
                                                int x1 = MySqlHelper.ExecuteNonQuery(CommandType.Text, inRrc1);
                                                string inRrc2 = $@" INSERT INTO qskj.R_Role_Channel (roleid, channelid, role_type, sort, is_delete, createuser, createtime, updateuser, updatetime)
                                             VALUES (2, {cuFili.carid}, 3, 0, 0, 'QskjBaseDataToDb', now(), 'QskjBaseDataToDb', now());";
                                                int x2 = MySqlHelper.ExecuteNonQuery(CommandType.Text, inRrc2);
                                                string inRrc3 = $@" INSERT INTO qskj.R_Role_Channel (roleid, channelid, role_type, sort, is_delete, createuser, createtime, updateuser, updatetime)
                                             VALUES (3, {cuFili.carid}, 3, 0, 0, 'QskjBaseDataToDb', now(), 'QskjBaseDataToDb', now());";
                                                int x3 = MySqlHelper.ExecuteNonQuery(CommandType.Text, inRrc3);
                                                Console.WriteLine($"配置车辆权限到固定角色{cuFili.carid}");
                                            }
                                            #endregion
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine($@"{item.car_numbers}本地数据库存在当前车辆信息处理异常：" + ex.Message);
                                    }
                                }
                                #endregion
                                #region 本地数据库不存在当前车辆信息
                                else
                                {
                                    try
                                    {
                                        int carid = 0;//出租车id
                                        #region 添加车辆到基础表
                                        string inCar = $@"INSERT INTO qskj.B_Taxi (license_plate, frame_number, terminalkey, color, bus_code, sort, is_delete, createuser, createtime, updateuser, updatetime, zl) 
                                                    VALUES ('{item.car_numbers}', '{item.code}', '{item.code}', '4','{item.car_numbers.Substring(1)}',0,0,'QskjBaseDataToDb',now(),'QskjBaseDataToDb',now(),'0');SELECT LAST_INSERT_ID();";
                                        if (!string.IsNullOrWhiteSpace(item.terminalkey))
                                        {
                                            inCar = $@"INSERT INTO qskj.B_Taxi (license_plate, frame_number, terminalkey, color, bus_code, sort, is_delete, createuser, createtime, updateuser, updatetime, zl,zlterminalkey,zltype) 
                                                    VALUES ('{item.car_numbers}', '{item.code}', '{item.terminalkey}', '4','{item.car_numbers.Substring(1)}',0,0,'QskjBaseDataToDb',now(),'QskjBaseDataToDb',now(),'1','{item.terminalkey}','{item.zltype}');SELECT LAST_INSERT_ID();";
                                        }
                                        object oc = MySqlHelper.ExecuteScalar(CommandType.Text, inCar);
                                        carid = oc == null ? 0 : Convert.ToInt32(oc);
                                        Console.WriteLine($"添加车辆到基础表{item.car_numbers}");
                                        #endregion
                                        #region 配置车辆权限到固定角色
                                        {
                                            string inRrc1 = $@" INSERT INTO qskj.R_Role_Channel (roleid, channelid, role_type, sort, is_delete, createuser, createtime, updateuser, updatetime)
                                            VALUES (1, {carid}, 3, 0, 0, 'QskjBaseDataToDb', now(), 'QskjBaseDataToDb', now());";
                                            MySqlHelper.ExecuteNonQuery(CommandType.Text, inRrc1);
                                            string inRrc2 = $@" INSERT INTO qskj.R_Role_Channel (roleid, channelid, role_type, sort, is_delete, createuser, createtime, updateuser, updatetime)
                                            VALUES (2, {carid}, 3, 0, 0, 'QskjBaseDataToDb', now(), 'QskjBaseDataToDb', now());";
                                            MySqlHelper.ExecuteNonQuery(CommandType.Text, inRrc2);
                                            string inRrc3 = $@" INSERT INTO qskj.R_Role_Channel (roleid, channelid, role_type, sort, is_delete, createuser, createtime, updateuser, updatetime)
                                            VALUES (3, {carid}, 3, 0, 0, 'QskjBaseDataToDb', now(), 'QskjBaseDataToDb', now());";
                                            MySqlHelper.ExecuteNonQuery(CommandType.Text, inRrc3);
                                            Console.WriteLine($"配置车辆权限到固定角色{carid}");
                                        }
                                        #endregion

                                        FilialeInfo cuFili = listFili.FirstOrDefault(p => p.name == ztFili);//判断是否存在中台车队名称
                                        int filialeid = 0;
                                        #region 不存在车队名称需要添加新车队
                                        if (cuFili == null)
                                        {
                                            string inFili = $@"insert into qskj.B_Taxi_Filiale(name,code,sort,is_delete,createuser,createtime,updateuser,updatetime)values('{ztFili}','{ztFili}',1,0,'QskjBaseDataToDb',now(),'QskjBaseDataToDb',now());SELECT LAST_INSERT_ID();";
                                            object of = MySqlHelper.ExecuteScalar(CommandType.Text, inFili);
                                            filialeid = of == null ? 0 : Convert.ToInt32(of);
                                            FilialeInfo info = new FilialeInfo();
                                            info.id = filialeid;
                                            info.name = ztFili;
                                            listFili.Add(info);
                                            string InfR = $@"  insert into qskj.R_Role_Filiale(roleid,filialeId,role_type,sort,is_delete,createuser,createtime,updateuser,updatetime)
                                                    values(1,{filialeid},3,0,0,'QskjBaseDataToDb',now(),'QskjBaseDataToDb',now()),(2,{filialeid},3,0,0,'QskjBaseDataToDb',now(),'QskjBaseDataToDb',now()),(3,{filialeid},3,0,0,'QskjBaseDataToDb',now(),'QskjBaseDataToDb',now());";
                                            MySqlHelper.ExecuteNonQuery(CommandType.Text, InfR);
                                            Console.WriteLine($"不存在车队名称需要添加新车队ztFili{ztFili}");
                                        }
                                        #endregion
                                        #region 存在车队名称删除原有的车队配置
                                        else
                                        {
                                            filialeid = cuFili.id;
                                            #region 删除原有的车队配置
                                            string deFili = $@"delete from qskj.R_TaxiFili_Taxi where taxiid in(select id from qskj.B_Taxi where license_plate='{item.car_numbers}')";
                                            MySqlHelper.ExecuteNonQuery(CommandType.Text, deFili);
                                            Console.WriteLine($"删除原有的车队配置car_numbers{item.car_numbers}");
                                            #endregion
                                        }
                                        #endregion

                                        #region 配置车辆通道信息
                                        {
                                            string inRrc1 = $@"INSERT INTO qskj.R_Taxi_Channel (taxiid, channelid, num, sort, is_delete, createuser, createtime, updateuser, updatetime, license_plate, filialeId, filialeName, companyId, companyName) 
                                                VALUES ({carid}, 180, 0, 0, 0, 'QskjBaseDataToDb', now(), 'QskjBaseDataToDb', now(), '{item.car_numbers}', {filialeid}, '{ztFili}', 1, '上海强生出租汽车有限公司');";
                                            MySqlHelper.ExecuteNonQuery(CommandType.Text, inRrc1);
                                            string inRrc2 = $@"INSERT INTO qskj.R_Taxi_Channel (taxiid, channelid, num, sort, is_delete, createuser, createtime, updateuser, updatetime, license_plate, filialeId, filialeName, companyId, companyName) 
                                                VALUES ({carid}, 181, 0, 0, 0, 'QskjBaseDataToDb', now(), 'QskjBaseDataToDb', now(), '{item.car_numbers}', {filialeid}, '{ztFili}', 1, '上海强生出租汽车有限公司');";
                                            MySqlHelper.ExecuteNonQuery(CommandType.Text, inRrc2);
                                            string inRrc3 = $@"INSERT INTO qskj.R_Taxi_Channel (taxiid, channelid, num, sort, is_delete, createuser, createtime, updateuser, updatetime, license_plate, filialeId, filialeName, companyId, companyName) 
                                                VALUES ({carid}, 182, 0, 0, 0, 'QskjBaseDataToDb', now(), 'QskjBaseDataToDb', now(), '{item.car_numbers}', {filialeid}, '{ztFili}', 1, '上海强生出租汽车有限公司');";
                                            MySqlHelper.ExecuteNonQuery(CommandType.Text, inRrc3);
                                            Console.WriteLine($"配置车辆通道信息{carid}");
                                        }
                                        #endregion

                                        #region 配置车辆车队归属信息
                                        string inRFiliCar = $@"insert into qskj.R_TaxiFili_Taxi(filialeid,taxiid,companyid,sort,is_delete,createuser,createtime,updateuser,updatetime)values({filialeid},{carid},1,1,0,'QskjBaseDataToDb',now(),'QskjBaseDataToDb',now());";
                                        MySqlHelper.ExecuteNonQuery(CommandType.Text, inRFiliCar);
                                        Console.WriteLine($"配置车辆车队归属信息filialeid{filialeid}carid{carid}");
                                        #endregion
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine($@"{item.car_numbers}本地数据库不存在当前车辆信息处理异常：" + ex.Message + JsonConvert.SerializeObject(ex));
                                    }
                                }
                                #endregion
                            }
                            #endregion
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("基础数据组织架构关系处理异常：" + ex.Message);
                }
                #endregion
                #region 大巴车基础数据组织架构关系处理
                try
                {
                    List<FilialeInfo> listFili = new List<FilialeInfo>();
                    #region 获取现有数据结构
                    string sqlFili = $@" select a.id,a.name,c.license_plate,c.id carid,e.id companyid,e.name companyname from qskj.B_Bus_Filiale a
                                         left join qskj.R_Filiale_Bus b on a.id=b.filialeid
                                         left join qskj.B_Bus c on b.busid=c.id
                                         left join qskj.R_Company_Filiale d on a.id=d.filialeid
                                         left join qskj.B_Bus_Company e on d.companyid=e.id";
                    DataTable dt = MySqlHelper.GetDataTable(CommandType.Text, sqlFili);
                    foreach (DataRow dr in dt.Rows)
                    {
                        FilialeInfo filialeInfo = new FilialeInfo();
                        filialeInfo.companyid = dr["companyid"] == DBNull.Value ? 0 : Convert.ToInt32(dr["companyid"]);
                        filialeInfo.companyname = dr["companyname"] == DBNull.Value ? "" : Convert.ToString(dr["companyname"]);
                        filialeInfo.id = dr["id"] == DBNull.Value ? 0 : Convert.ToInt32(dr["id"]);
                        filialeInfo.name = dr["name"] == DBNull.Value ? "" : Convert.ToString(dr["name"]);
                        filialeInfo.carid = dr["carid"] == DBNull.Value ? 0 : Convert.ToInt32(dr["carid"]);
                        filialeInfo.license_plate = dr["license_plate"] == DBNull.Value ? "" : Convert.ToString(dr["license_plate"]);
                        listFili.Add(filialeInfo);
                    }

                    List<FilialeInfo> sqList = new List<FilialeInfo>();
                    {
                        string sq = $@" SELECT * FROM qskj.B_Bus_Filiale";
                        DataTable dtSq = MySqlHelper.GetDataTable(CommandType.Text, sq);
                        foreach (DataRow dr in dtSq.Rows)
                        {
                            FilialeInfo filialeInfo = new FilialeInfo();
                            filialeInfo.id = dr["id"] == DBNull.Value ? 0 : Convert.ToInt32(dr["id"]);
                            filialeInfo.name = dr["name"] == DBNull.Value ? "" : Convert.ToString(dr["name"]);
                            sqList.Add(filialeInfo);
                        }
                    }
                    List<FilialeInfo> sqBusList = new List<FilialeInfo>();
                    {
                        string sq = $@" SELECT * FROM qskj.B_Bus";
                        DataTable dtSq = MySqlHelper.GetDataTable(CommandType.Text, sq);
                        foreach (DataRow dr in dtSq.Rows)
                        {
                            FilialeInfo filialeInfo = new FilialeInfo();
                            filialeInfo.carid = dr["id"] == DBNull.Value ? 0 : Convert.ToInt32(dr["id"]);
                            filialeInfo.license_plate = dr["license_plate"] == DBNull.Value ? "" : Convert.ToString(dr["license_plate"]);
                            sqBusList.Add(filialeInfo);
                        }
                    }
                    #endregion
                    foreach (var item in obj.data.dataArray)
                    {
                        if (item.car_assets_name_name != "上海强生出租汽车有限公司")
                        {
                            #region 车牌号车队名与现有结构一致不作处理
                            if (listFili.Exists(p => p.license_plate == item.car_numbers && p.name == item.dep))
                            {
                                continue;
                            }
                            #endregion
                            #region 车牌号车队名与现有结构不一致
                            else
                            {
                                string ztFili = item.dep;//中台数据库--当前车辆现归属车队名
                                FilialeInfo cuCar = listFili.FirstOrDefault(p => p.license_plate == item.car_numbers);//本地数据库中是否存在当前车辆
                                #region 本地数据库存在当前车辆信息
                                if (cuCar != null)
                                {
                                    try
                                    {
                                        FilialeInfo cuFili = listFili.FirstOrDefault(p => p.name == ztFili);//判断是否存在中台车队名称
                                        int filialeid = 0;
                                        #region 不存在车队名称需要添加新车队
                                        if (cuFili == null)
                                        {
                                            string inFili = $@"insert into qskj.B_Bus_Filiale(name,code,sort,is_delete,createuser,createtime,updateuser,updatetime)values('{ztFili}','{ztFili}',1,0,'QskjBaseDataToDb',now(),'QskjBaseDataToDb',now());SELECT LAST_INSERT_ID();";
                                            object o = MySqlHelper.ExecuteScalar(CommandType.Text, inFili);
                                            filialeid = o == DBNull.Value ? 0 : Convert.ToInt32(o);
                                            FilialeInfo info = new FilialeInfo();
                                            info.id = filialeid;
                                            info.name = ztFili;
                                            listFili.Add(info);
                                        }
                                        #endregion
                                        #region 存在车队名称删除原有的车队配置
                                        else
                                        {
                                            filialeid = cuFili.id;
                                            #region 删除原有的车队配置
                                            string deFili = $@"delete from qskj.R_Filiale_Bus where busid in(select id from qskj.B_Bus where license_plate='{item.car_numbers}')";
                                            MySqlHelper.ExecuteNonQuery(CommandType.Text, deFili);
                                            #endregion
                                        }
                                        #endregion
                                        #region 配置车辆车队归属信息
                                        string inRFiliCar = $@"insert into qskj.R_Filiale_Bus(filialeid,busid,sort,is_delete,createuser,createtime,updateuser,updatetime)values({filialeid},{cuCar.carid},1,0,'QskjBaseDataToDb',now(),'QskjBaseDataToDb',now());";
                                        MySqlHelper.ExecuteNonQuery(CommandType.Text, inRFiliCar);
                                        #endregion
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine($@"{item.car_numbers}本地数据库存在当前车辆信息处理异常：" + ex.Message);
                                    }
                                }
                                #endregion
                                #region 重新组织车辆车队关系
                                else
                                {
                                    FilialeInfo fi = sqList.FirstOrDefault(p => p.name == item.dep);//查询车队信息
                                                                                                    //Console.WriteLine(JsonConvert.SerializeObject(fi));
                                    FilialeInfo fiBus = sqBusList.FirstOrDefault(p => p.license_plate == item.car_numbers);//查询车队信息
                                                                                                                           //Console.WriteLine(JsonConvert.SerializeObject(fiBus));
                                    if (fi != null && fiBus != null && fi?.id > 0 && fiBus?.carid > 0)
                                    {
                                        #region 配置车辆车队归属信息
                                        string inRFiliCar = $@"insert into qskj.R_Filiale_Bus(filialeid,busid,sort,is_delete,createuser,createtime,updateuser,updatetime)values({fi.id},{fiBus.carid},1,0,'QskjBaseDataToDb',now(),'QskjBaseDataToDb',now());";
                                        MySqlHelper.ExecuteNonQuery(CommandType.Text, inRFiliCar);
                                        #endregion
                                    }
                                }
                                #endregion
                                #region 本地数据库不存在当前车辆信息
                                //else
                                //{
                                //    try
                                //    {
                                //        int carid = 0;//出租车id
                                //        #region 添加车辆到基础表
                                //        string inCar = $@"INSERT INTO qskj.B_Bus (license_plate, frame_number, terminalkey, color, bus_code, sort, is_delete, createuser, createtime, updateuser, updatetime, zl) 
                                //                    VALUES ('{item.car_numbers}', '{item.code}', '{item.code}', '4','{item.car_numbers.Substring(1)}',0,0,'QskjBaseDataToDb',now(),'QskjBaseDataToDb',now(),'0');SELECT LAST_INSERT_ID();";
                                //        object oc = MySqlHelper.ExecuteScalar(CommandType.Text, inCar);
                                //        carid = oc == DBNull.Value ? 0 : Convert.ToInt32(oc);
                                //        #endregion
                                //        #region 配置车辆权限到固定角色
                                //        {
                                //            string inRrc = $@" INSERT INTO qskj.R_Role_Channel (roleid, channelid, role_type, sort, is_delete, createuser, createtime, updateuser, updatetime)
                                //            VALUES ('1', '{carid}', '2', '0', '0', 'QskjBaseDataToDb', now(), 'QskjBaseDataToDb', now()),
                                //                    ('2', '{carid}', '2', '0', '0', 'QskjBaseDataToDb', now(), 'QskjBaseDataToDb', now()),
                                //                    ('3', '{carid}', '2', '0', '0', 'QskjBaseDataToDb', now(), 'QskjBaseDataToDb', now());";
                                //            MySqlHelper.ExecuteNonQuery(CommandType.Text, inRrc);
                                //        }
                                //        #endregion

                                //        FilialeInfo cuFili = listFili.FirstOrDefault(p => p.name == ztFili);//判断是否存在中台车队名称
                                //        int filialeid = 0;
                                //        #region 不存在车队名称需要添加新车队
                                //        if (cuFili == null)
                                //        {
                                //            string inFili = $@"insert into qskj.B_Bus_Filiale(name,code,sort,is_delete,createuser,createtime,updateuser,updatetime)values('{ztFili}','{ztFili}',1,0,'QskjBaseDataToDb',now(),'QskjBaseDataToDb',now());SELECT LAST_INSERT_ID();";
                                //            object of = MySqlHelper.ExecuteScalar(CommandType.Text, inFili);
                                //            filialeid = of == DBNull.Value ? 0 : Convert.ToInt32(of);
                                //            FilialeInfo info = new FilialeInfo();
                                //            info.id = filialeid;
                                //            info.name = ztFili;
                                //            listFili.Add(info);
                                //        }
                                //        #endregion
                                //        #region 存在车队名称删除原有的车队配置
                                //        else
                                //        {
                                //            filialeid = cuFili.id;
                                //            #region 删除原有的车队配置
                                //            string deFili = $@"delete from qskj.R_Filiale_Bus where taxiid in(select id from qskj.B_Bus where license_plate='{item.car_numbers}')";
                                //            MySqlHelper.ExecuteNonQuery(CommandType.Text, deFili);
                                //            #endregion
                                //        }
                                //        #endregion

                                //        #region 配置车辆通道信息
                                //        {
                                //            string inRrc = $@"INSERT INTO qskj.R_Bus_Channel (busid, channelid, num, sort, is_delete, createuser, createtime, updateuser, updatetime, license_plate, filialeId, filialeName, companyId, companyName) 
                                //                       VALUES 
                                //                       ('{carid}', '174', '0', '0', '0', 'QskjBaseDataToDb', now(), 'QskjBaseDataToDb', now(), '{item.car_numbers}', '{filialeid}', '{ztFili}', '', ''),
                                //                       ('{carid}', '175', '0', '0', '0', 'QskjBaseDataToDb', now(), 'QskjBaseDataToDb', now(), '{item.car_numbers}', '{filialeid}', '{ztFili}', '', ''),
                                //                       ('{carid}', '176', '0', '0', '0', 'QskjBaseDataToDb', now(), 'QskjBaseDataToDb', now(), '{item.car_numbers}', '{filialeid}', '{ztFili}', '', ''),
                                //                       ('{carid}', '177', '0', '0', '0', 'QskjBaseDataToDb', now(), 'QskjBaseDataToDb', now(), '{item.car_numbers}', '{filialeid}', '{ztFili}', '', ''),
                                //                       ('{carid}', '178', '0', '0', '0', 'QskjBaseDataToDb', now(), 'QskjBaseDataToDb', now(), '{item.car_numbers}', '{filialeid}', '{ztFili}', '', ''),
                                //                       ('{carid}', '179', '0', '0', '0', 'QskjBaseDataToDb', now(), 'QskjBaseDataToDb', now(), '{item.car_numbers}', '{filialeid}', '{ztFili}', '', '');";
                                //            MySqlHelper.ExecuteNonQuery(CommandType.Text, inRrc);
                                //        }
                                //        #endregion

                                //        #region 配置车辆车队归属信息
                                //        string inRFiliCar = $@"insert into qskj.R_Filiale_Bus(filialeid,busid,sort,is_delete,createuser,createtime,updateuser,updatetime)values({filialeid},{carid},1,0,'QskjBaseDataToDb',now(),'QskjBaseDataToDb',now());";
                                //        MySqlHelper.ExecuteNonQuery(CommandType.Text, inRFiliCar);
                                //        #endregion
                                //    }
                                //    catch (Exception ex)
                                //    {
                                //        Console.WriteLine($@"{item.car_numbers}本地数据库不存在当前车辆信息处理异常：" + ex.Message + JsonConvert.SerializeObject(ex));
                                //    }
                                //}
                                #endregion
                            }
                            #endregion
                        }
                    }
                    List<FilialeInfo> listFili1 = listFili.GroupBy(p => new { p.id, p.name, p.companyid, p.companyname })
                        .Select(p => new FilialeInfo { id = p.Key.id, name = p.Key.name, companyid = p.Key.companyid, companyname = p.Key.companyname }).ToList();
                    List<ZtDataResInfo> ztData = obj.data.dataArray.GroupBy(p => new { p.dep, p.car_assets_name_name }).Select(p => new ZtDataResInfo { dep = p.Key.dep, car_assets_name_name = p.Key.car_assets_name_name }).ToList();
                    foreach (var item in ztData)
                    {
                        if (item.car_assets_name_name != "上海强生出租汽车有限公司")
                        {
                            #region 车队名公司名与现有结构一致不作处理
                            if (listFili1.Exists(p => p.name == item.dep && p.companyname == item.car_assets_name_name))
                            {
                                continue;
                            }
                            #endregion
                            #region 车队名公司名与现有结构不一致
                            else
                            {
                                string ztCompany = item.car_assets_name_name;//中台数据库--当前车队现归属公司名
                                FilialeInfo cuFili = listFili1.FirstOrDefault(p => p.name == item.dep);//本地数据库中是否存在当前车队
                                #region 本地数据库存在当前车队信息
                                if (cuFili != null)
                                {
                                    try
                                    {
                                        FilialeInfo cuCom = listFili1.FirstOrDefault(p => p.companyname == ztCompany);//判断是否存在中台公司名称
                                        int companyid = 0;
                                        #region 不存在公司名称需要添加新公司
                                        if (cuCom == null)
                                        {
                                            string inCompany = $@"insert into qskj.B_Bus_Company(name,code,sort,is_delete,createuser,createtime,updateuser,updatetime)values('{ztCompany}','{ztCompany}',1,0,'QskjBaseDataToDb',now(),'QskjBaseDataToDb',now());SELECT LAST_INSERT_ID();";
                                            object o = MySqlHelper.ExecuteScalar(CommandType.Text, inCompany);
                                            companyid = o == DBNull.Value ? 0 : Convert.ToInt32(o);
                                            FilialeInfo info = new FilialeInfo();
                                            info.companyid = companyid;
                                            info.companyname = ztCompany;
                                            listFili1.Add(info);
                                        }
                                        #endregion
                                        #region 存在公司名称删除原有的公司配置
                                        else
                                        {
                                            companyid = cuCom.companyid;
                                            #region 删除原有的车队配置
                                            string deFili = $@"delete from qskj.R_Company_Filiale where filialeid in(select id from qskj.B_Bus_Filiale where name='{item.dep}')";
                                            MySqlHelper.ExecuteNonQuery(CommandType.Text, deFili);
                                            #endregion
                                        }
                                        #endregion
                                        #region 配置车队公司归属信息
                                        string inRFiliCar = $@"insert into qskj.R_Company_Filiale(companyid,filialeid,sort,is_delete,createuser,createtime,updateuser,updatetime)values({companyid},{cuFili.id},1,0,'QskjBaseDataToDb',now(),'QskjBaseDataToDb',now());";
                                        MySqlHelper.ExecuteNonQuery(CommandType.Text, inRFiliCar);
                                        #endregion
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine($@"{item.car_numbers}本地数据库存在当前车辆信息处理异常：" + ex.Message);
                                    }
                                }
                                #endregion
                                #region 本地数据库不存在当前车队信息
                                else
                                {
                                    try
                                    {
                                        int filiId = 0;//车队id
                                        #region 添加车队到基础表
                                        string inFili = $@"INSERT INTO qskj.B_Bus_Filiale (name,code,sort,is_delete,createuser,createtime,updateuser,updatetime) 
                                                    VALUES ('{item.dep}', '{item.dep}', 0,0,'QskjBaseDataToDb',now(),'QskjBaseDataToDb',now());SELECT LAST_INSERT_ID();";
                                        object oc = MySqlHelper.ExecuteScalar(CommandType.Text, inFili);
                                        filiId = oc == DBNull.Value ? 0 : Convert.ToInt32(oc);
                                        #endregion

                                        FilialeInfo cuCom = listFili1.FirstOrDefault(p => p.companyname == item.car_assets_name_name);//判断是否存在中台公司名称
                                        int companyid = 0;
                                        #region 不存在公司名称需要添加新公司
                                        if (cuCom == null)
                                        {
                                            string inCompany = $@"insert into qskj.B_Bus_Company(name,code,sort,is_delete,createuser,createtime,updateuser,updatetime)values('{ztCompany}','{ztCompany}',0,0,'QskjBaseDataToDb',now(),'QskjBaseDataToDb',now());SELECT LAST_INSERT_ID();";
                                            object o = MySqlHelper.ExecuteScalar(CommandType.Text, inCompany);
                                            companyid = o == DBNull.Value ? 0 : Convert.ToInt32(o);
                                            FilialeInfo info = new FilialeInfo();
                                            info.companyid = companyid;
                                            info.companyname = ztCompany;
                                            listFili1.Add(info);
                                        }
                                        #endregion
                                        #region 存在公司名称删除原有的公司配置
                                        else
                                        {
                                            companyid = cuCom.companyid;
                                            #region 删除原有的车队配置
                                            string deFili = $@"delete from qskj.R_Company_Filiale where filialeid in(select id from qskj.B_Bus_Filiale where name='{item.dep}')";
                                            MySqlHelper.ExecuteNonQuery(CommandType.Text, deFili);
                                            #endregion
                                        }
                                        #endregion
                                        #region 配置车队公司归属信息
                                        string inRFiliCar = $@"insert into qskj.R_Company_Filiale(companyid,filialeid,sort,is_delete,createuser,createtime,updateuser,updatetime)values({companyid},{filiId},1,0,'QskjBaseDataToDb',now(),'QskjBaseDataToDb',now());";
                                        MySqlHelper.ExecuteNonQuery(CommandType.Text, inRFiliCar);
                                        #endregion
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine($@"{item.car_numbers}本地数据库不存在当前车辆信息处理异常：" + ex.Message + JsonConvert.SerializeObject(ex));
                                    }
                                }
                                #endregion
                            }
                            #endregion
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("大巴车基础数据组织架构关系处理异常：" + ex.Message);
                }
                #endregion
                #region 组织架构同步后重新生成国标码
                {
                    try
                    {
                        string sqlDelDev = $@"delete from qskj.B_Device where model='CAR'";
                        MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sqlDelDev);
                        string tokeninfo = HttpHelper.GetToken().Result;
                        TokenInfo token1 = new TokenInfo();
                        token1 = JsonConvert.DeserializeObject<TokenInfo>(tokeninfo);
                        Console.WriteLine(token1);
                        HttpHelper.GetProtectDeviceCode0(token1?.token);
                        HttpHelper.GetProtectDeviceCode1(token1?.token);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($@"重新生成国标码处理异常：" + ex.Message + JsonConvert.SerializeObject(ex));
                    }
                }
                #endregion
                UpdateRoleFiliale();//角色车队权限，角色车辆权限变动后同步
                #region 清除本地表中比中台数据多出的出租车
                {
                    string sqlDel = $@"delete from qskj.B_Taxi where id>0 and license_plate not in
                                        (
	                                        select  car_numbers from qskjrecord.B_BusZT{dtStr} group by car_numbers
                                        )";
                    MySqlHelper.ExecuteNonQuery(CommandType.Text, sqlDel);
                }
                #region 直连车辆数据写入Redis
                {

                }
                #endregion
                #endregion
            }
            catch (Exception e)
            {
                Console.WriteLine("读取中台出租车信息异常：" + e.Message);
            }
        }
        /// <summary>
        /// 车辆变动车队关系，权限数据更新调整
        /// </summary>
        public static void UpdateRoleFiliale()
        {
            try
            {
                List<RoleFilialeVehicel> roleFiliBus = new List<RoleFilialeVehicel>();
                List<RoleFilialeVehicel> roleFiliCar = new List<RoleFilialeVehicel>();
                #region 查询车队关联车辆权限
                //此处查询||角色车队权限||，如果角色车队权限没有配置，即使配置车辆角色权限也会被清除权限
                string sql = $@"select a.filialeId,b.busid,c.taxiid,a.role_type,a.roleid   from qskj.R_Role_Filiale a
                            left join (
	                            select ba.filialeid,ba.busid from qskj.R_Filiale_Bus ba
                                join qskj.B_Bus bb on ba.busid=bb.id
                            )b on a.filialeid=b.filialeid and a.role_type=2
                            left join (
	                            select ca.filialeid,ca.taxiid from qskj.R_TaxiFili_Taxi ca
                                join qskj.B_Taxi cb on ca.taxiid=cb.id
                            )c on a.filialeid=c.filialeid and a.role_type=3

                            where (a.role_type=2 or a.role_type=3)";
                DataTable dtRoleFiliDt = MySqlHelper.GetDataTable(CommandType.Text, sql);
                foreach (DataRow item in dtRoleFiliDt.Rows)
                {
                    RoleFilialeVehicel rf = new RoleFilialeVehicel();
                    rf.RoleTypeId = item["role_type"] == DBNull.Value ? 0 : Convert.ToInt32(item["role_type"]);
                    rf.RoleId = item["roleid"] == DBNull.Value ? 0 : Convert.ToInt32(item["roleid"]);
                    //rf.FilialeId = item["filialeId"] == DBNull.Value ? 0 : Convert.ToInt32(item["filialeId"]);
                    if (rf.RoleTypeId == 2)
                    {
                        rf.VehicleId = item["busid"] == DBNull.Value ? 0 : Convert.ToInt32(item["busid"]);
                        roleFiliBus.Add(rf);
                    }
                    if (rf.RoleTypeId == 3)
                    {
                        rf.VehicleId = item["taxiid"] == DBNull.Value ? 0 : Convert.ToInt32(item["taxiid"]);
                        roleFiliCar.Add(rf);
                    }
                }
                #endregion
                List<RoleFilialeVehicel> roleBus = new List<RoleFilialeVehicel>();
                #region 查询角色大巴权限
                {
                    //此处查询的是车辆角色权限
                    string sqlRoleBus = $@"select da.roleid,da.role_type,da.channelid from qskj.R_Role_Channel da 
                                        join qskj.B_Bus db on da.channelid=db.id 
	                                    where  da.role_type=2";
                    DataTable dt = MySqlHelper.GetDataTable(CommandType.Text, sqlRoleBus);
                    foreach (DataRow item in dt.Rows)
                    {
                        RoleFilialeVehicel rf = new RoleFilialeVehicel();
                        rf.RoleTypeId = item["role_type"] == DBNull.Value ? 0 : Convert.ToInt32(item["role_type"]);
                        rf.RoleId = item["roleid"] == DBNull.Value ? 0 : Convert.ToInt32(item["roleid"]);
                        rf.VehicleId = item["channelid"] == DBNull.Value ? 0 : Convert.ToInt32(item["channelid"]);
                        roleBus.Add(rf);
                    }
                }
                #endregion
                List<RoleFilialeVehicel> roleCar = new List<RoleFilialeVehicel>();
                #region 查询角色出租权限
                {
                    //此处查询的是车辆角色权限
                    string sqlRoleCar = $@"select ea.roleid,ea.role_type,ea.channelid from qskj.R_Role_Channel ea 
                                        join qskj.B_Taxi eb on ea.channelid=eb.id 
	                                    where  ea.role_type=3";
                    DataTable dt = MySqlHelper.GetDataTable(CommandType.Text, sqlRoleCar);
                    foreach (DataRow item in dt.Rows)
                    {
                        RoleFilialeVehicel rf = new RoleFilialeVehicel();
                        rf.RoleTypeId = item["role_type"] == DBNull.Value ? 0 : Convert.ToInt32(item["role_type"]);
                        rf.RoleId = item["roleid"] == DBNull.Value ? 0 : Convert.ToInt32(item["roleid"]);
                        rf.VehicleId = item["channelid"] == DBNull.Value ? 0 : Convert.ToInt32(item["channelid"]);
                        roleCar.Add(rf);
                    }
                }
                #endregion
                #region 处理调出车辆
                List<RoleFilialeVehicel> roleFiliBusDel = new List<RoleFilialeVehicel>();
                foreach (var item in roleBus)
                {
                    var d = roleFiliBus.Exists(p => p.RoleId == item.RoleId && p.VehicleId == item.VehicleId);
                    if (d == false)
                    {
                        roleFiliBusDel.Add(item);
                    }
                }
                foreach (var item in roleCar)
                {
                    var d = roleFiliCar.Exists(p => p.RoleId == item.RoleId && p.VehicleId == item.VehicleId);
                    if (d == false)
                    {
                        roleFiliBusDel.Add(item);
                    }
                }
                //List<RoleFilialeVehicel> roleFiliBusDel = roleBus.Except(roleFiliBus).ToList();
                //List<RoleFilialeVehicel> roleFiliCarDel = roleCar.Except(roleFiliCar).ToList();
                //roleFiliBusDel.AddRange(roleFiliCarDel);
                foreach (var item in roleFiliBusDel)
                {
                    string deSql = $@"delete from qskj.R_Role_Channel where roleid={item.RoleId} and channelid={item.VehicleId} and role_type={item.RoleTypeId}";
                    MySqlHelper.ExecuteNonQuery(CommandType.Text, deSql);
                }
                #endregion
                #region 处理调入车辆 
                List<RoleFilialeVehicel> roleFiliBusAdd = new List<RoleFilialeVehicel>();
                foreach (var item in roleFiliBus)
                {
                    var d = roleBus.Exists(p => p.RoleId == item.RoleId && p.VehicleId == item.VehicleId);
                    if (d == false)
                    {
                        roleFiliBusAdd.Add(item);
                    }
                }
                foreach (var item in roleFiliCar)
                {
                    var d = roleCar.Exists(p => p.RoleId == item.RoleId && p.VehicleId == item.VehicleId);
                    if (d == false)
                    {
                        roleFiliBusAdd.Add(item);
                    }
                }
                //List<RoleFilialeVehicel> roleFiliBusAdd = roleFiliBus.Except(roleBus).ToList();
                //List<RoleFilialeVehicel> roleFiliCarAdd = roleFiliCar.Except(roleCar).ToList();
                //roleFiliBusAdd.AddRange(roleFiliCarAdd);
                foreach (var item in roleFiliBusAdd)
                {
                    string inSql = $@"insert into qskj.R_Role_Channel(roleid,channelid,role_type,sort,is_delete,createuser,createtime,updateuser,updatetime)
                                    values({item.RoleId},{item.VehicleId},{item.RoleTypeId},0,0,'UpdateRoleFiliale',now(),'UpdateRoleFiliale',now())";
                    MySqlHelper.ExecuteNonQuery(CommandType.Text, inSql);
                }
                #endregion

            }
            catch (Exception e)
            {
                Console.WriteLine("车辆变动车队关系，权限数据更新调整异常：" + e.Message + JsonConvert.SerializeObject(e));
            }
        }
        /// <summary>
        /// 中台《出租车驾驶员绑定》基础数据
        /// </summary>
        public static void UpdateCarDriverData()
        {
            CSRedisClient? cSRedisClient5 = null;
            string? token = string.Empty;
            try
            {
                //出租数据
                if (cSRedisClient5 == null)
                {
                    cSRedisClient5 = RedisHelp.GetInstance5();
                }
                //string dtStrPre = DateTime.Now.AddDays(-5).ToString("yyyyMMdd");
                //string sqlPre = $@"drop table if exists qskjrecord.B_TaxiCarDriverZT{dtStrPre}";
                //MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sqlPre);
                string dtStr = DateTime.Now.ToString("yyyyMMdd");
                if (DateTime.Now.Hour < 7)
                {
                    string exists = $@"SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'qskjrecord' AND TABLE_NAME = 'B_TaxiCarDriverZT{dtStr}';";
                    object resExi = MySqlHelper.ExecuteScalar(CommandType.Text, exists);
                    if (resExi == null || resExi == DBNull.Value)
                    {
                        string sql = $@"create table IF NOT EXISTS qskjrecord.B_TaxiCarDriverZT{dtStr}
                        (
                           id                   bigint not null auto_increment,
                           car_numbers            varchar(50),
                           name                 varchar(50),
                           permit_number          varchar(50),
                           day_no                  varchar(50),
                           month_hudi           varchar(50),
                           duty_type            varchar(50), 
                           primary key (id)
                        );";
                        MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sql);
                    }
                    //string sqlPreBus = $@"drop table if exists qskjrecord.B_BusDriverBindZT{dtStrPre}";
                    //MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sqlPreBus);
                    string exists1 = $@"SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'qskjrecord' AND TABLE_NAME = 'B_BusDriverBindZT{dtStr}';";
                    object resExi1 = MySqlHelper.ExecuteScalar(CommandType.Text, exists1);
                    if (resExi1 == null || resExi1 == DBNull.Value)
                    {
                        string sqlBus = $@"create table IF NOT EXISTS qskjrecord.B_BusDriverBindZT{dtStr}
                        (
                           id                   bigint not null auto_increment,
                           duty_type              varchar(50),
                           permit_number         varchar(50),
                           day_no                 varchar(500),
                           name                  varchar(50),
                           month_hudi        varchar(50),
                           car_numbers                  varchar(50), 
                           primary key (id)
                        );";
                        MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sqlBus);
                    }
                }

                string sqlCount = $@"select count(*) from qskjrecord.B_BusDriverBindZT{dtStr}";
                if (Convert.ToInt32(MySqlHelper.ExecuteScalar(CommandType.Text, sqlCount)) > 0)
                {
                    Console.WriteLine(DateTime.Now + "中台《出租车驾驶员绑定》数据已读取成功");
                    return;
                }
                //读取中台《出租车驾驶员绑定》数据
                if (string.IsNullOrEmpty(token))
                {
                    try
                    {
                        ZtTokenDataInfo response = JsonConvert.DeserializeObject<ZtTokenDataInfo>(HttpHelper.GetZtToken().Result);
                        if (response == null)
                        {
                            Console.WriteLine("获取token失败response为空");
                            return;
                        }
                        if (string.IsNullOrEmpty(response.data))
                        {
                            Console.WriteLine("获取token失败response.data为空");
                            return;
                        }
                        token = response.data;

                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("获取token异常：" + e);
                    }
                }
                var str = HttpHelper.GetZtCarDriver(token).Result;
                ZtDataObj<ZtDataResCarDriverInfo> obj = JsonConvert.DeserializeObject<ZtDataObj<ZtDataResCarDriverInfo>>(str);
                if (obj == null || obj.data == null || string.IsNullOrEmpty(obj.data.total) || obj.data.total == "0")
                {
                    Console.WriteLine(DateTime.Now + "读取中台《出租车驾驶员绑定》数据" + str);

                    string dtStr1 = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
                    string insertSql1 = $@"insert into qskjrecord.B_TaxiCarDriverZT{dtStr}(car_numbers,name,permit_number,day_no,month_hudi,duty_type)
                                        select car_numbers,name,permit_number,day_no,month_hudi,duty_type from  qskjrecord.B_TaxiCarDriverZT{dtStr1}";
                    MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, insertSql1);
                    string insertSql2 = $@"insert into qskjrecord.B_BusDriverBindZT{dtStr}(duty_type,permit_number,day_no,name,month_hudi,car_numbers)
                                        select duty_type,permit_number,day_no,name,month_hudi,car_numbers from  qskjrecord.B_TaxiCarDriverZT{dtStr1}";
                    MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, insertSql2);
                }
                foreach (var item in obj.data.dataArray)
                {
                    string insertSql = $@"insert into qskjrecord.B_TaxiCarDriverZT{dtStr}(car_numbers,name,permit_number,day_no,month_hudi,duty_type)
                                        values('{item.car_numbers}','{item.name}','{item.permit_number}','{item.day_no}','{item.month_hudi}','{item.duty_type}')";
                    MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, insertSql);
                    if (!string.IsNullOrWhiteSpace(item.permit_number))
                    {
                        string dr = cSRedisClient5.Get(item.permit_number);//获取驾驶员信息
                        cSRedisClient5.Set(item.car_numbers, dr);//设置车辆驾驶员信息
                    }
                }
                //大巴数据
                //ZtDataObj<ZtBusDriverBindData> objBus = JsonConvert.DeserializeObject<ZtDataObj<ZtBusDriverBindData>>(str);
                foreach (var item in obj.data.dataArray)
                {
                    string insertSql = $@"insert into qskjrecord.B_BusDriverBindZT{dtStr}(duty_type,permit_number,day_no,name,month_hudi,car_numbers)
                                        values('{item.duty_type}','{item.permit_number}','{item.day_no}','{item.name}','{item.month_hudi}','{item.car_numbers}')";
                    MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, insertSql);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("读取出租车驾驶员绑定排班信息异常" + e.Message);
            }
        }
        /// <summary>
        /// 中台出租车《驾驶员》基础数据
        /// </summary>
        public static void UpdateDriverData()
        {
            CSRedisClient? cSRedisClient5 = null;
            string? token = string.Empty;
            if (cSRedisClient5 == null)
            {
                cSRedisClient5 = RedisHelp.GetInstance5();
            }
            try
            {
                //出租数据
                //string dtStrPre = DateTime.Now.AddDays(-5).ToString("yyyyMMdd");
                //string sqlPre = $@"drop table if exists qskjrecord.B_TaxiDriverZT{dtStrPre}";
                //MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sqlPre);
                string dtStr = DateTime.Now.ToString("yyyyMMdd");
                if (DateTime.Now.Hour < 7)
                {
                    string exists = $@"SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'qskjrecord' AND TABLE_NAME = 'B_TaxiDriverZT{dtStr}';";
                    object resExi = MySqlHelper.ExecuteScalar(CommandType.Text, exists);
                    if (resExi == null || resExi == DBNull.Value)
                    {
                        string sql = $@"create table IF NOT EXISTS qskjrecord.B_TaxiDriverZT{dtStr}
                        (
                           id                   bigint not null auto_increment,
                           id_card              varchar(50),
                           work_numbers         varchar(50),
                           name                 varchar(50),
                           dep                  varchar(50),
                           permit_number        varchar(50),
                           sex                  varchar(50),
                           birthday             varchar(50), 
                           head_url             text, 
                           first_get_time       varchar(50),  
                           phone       varchar(50),  
                           primary key (id)
                        );";
                        MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sql);
                    }
                    //string sqlPreBus = $@"drop table if exists qskjrecord.B_BusDriverZT{dtStrPre}";
                    //MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sqlPreBus);
                    string exists1 = $@"SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'qskjrecord' AND TABLE_NAME = 'B_BusDriverZT{dtStr}';";
                    object resExi1 = MySqlHelper.ExecuteScalar(CommandType.Text, exists1);
                    if (resExi1 == null || resExi1 == DBNull.Value)
                    {
                        string sqlBus = $@"create table IF NOT EXISTS qskjrecord.B_BusDriverZT{dtStr}
                        (
                           id                   bigint not null auto_increment,
                           birthday              varchar(50),
                           work_numbers         varchar(50),
                           head_url                 varchar(500),
                           permit_number                  varchar(50),
                           sex        varchar(50),
                           first_get_time                  varchar(50),
                           id_card             varchar(50), 
                           name             varchar(50),  
                           dep       varchar(50),   
                           phone       varchar(50),   
                           primary key (id)
                        );";
                        MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sqlBus);
                    }
                }

                string sqlCount = $@"select count(*) from qskjrecord.B_BusDriverZT{dtStr}";
                if (Convert.ToInt32(MySqlHelper.ExecuteScalar(CommandType.Text, sqlCount)) > 0)
                {
                    Console.WriteLine(DateTime.Now + "中台中台出租车的《驾驶员》数据已读取成功");
                    return;
                }
                //读取中台出租车的《驾驶员》数据
                if (string.IsNullOrEmpty(token))
                {
                    try
                    {
                        ZtTokenDataInfo response = JsonConvert.DeserializeObject<ZtTokenDataInfo>(HttpHelper.GetZtToken().Result);
                        if (response == null)
                        {
                            Console.WriteLine("获取token失败response为空");
                            return;
                        }
                        if (string.IsNullOrEmpty(response.data))
                        {
                            Console.WriteLine("获取token失败response.data为空");
                            return;
                        }
                        token = response.data;

                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("获取token异常：" + e);
                    }
                }
                var str = HttpHelper.GetZtDriver(token).Result;
                ZtDataObj<ZtDataResDriverInfo> obj = JsonConvert.DeserializeObject<ZtDataObj<ZtDataResDriverInfo>>(str);
                if (obj == null || obj.data == null || string.IsNullOrEmpty(obj.data.total) || obj.data.total == "0")
                {
                    Console.WriteLine(DateTime.Now + "读取中台出租车的《驾驶员》数据" + str);
                    string dtStr1 = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
                    string insertSql1 = $@"insert into qskjrecord.B_TaxiDriverZT{dtStr}(id_card,work_numbers,name,dep,permit_number,sex,birthday,head_url,first_get_time,phone)
                                        select id_card,work_numbers,name,dep,permit_number,sex,birthday,head_url,first_get_time,phone from  qskjrecord.B_TaxiCarDriverZT{dtStr1}";
                    MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, insertSql1);
                    string insertSql2 = $@"insert into qskjrecord.B_BusDriverZT{dtStr}(birthday,work_numbers,head_url,permit_number,sex,first_get_time,id_card,name,dep,phone)
                                        select birthday,work_numbers,head_url,permit_number,sex,first_get_time,id_card,name,dep,phone from  qskjrecord.B_TaxiCarDriverZT{dtStr1}";
                    MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, insertSql2);
                }
                foreach (var item in obj.data.dataArray)
                {
                    //cSRedisClient5.Set(item.work_numbers, item.id_card + "_" + item.work_numbers + "_" + item.name + "_" + item.head_url);//出租车驾驶员写入Redis
                    if (string.IsNullOrEmpty(item.permit_number))
                    {
                        item.permit_number = item.work_numbers;
                    }
                    cSRedisClient5.Set(item.id_card, item.id_card + ";" + item.permit_number + ";" + item.name + ";" + item.head_url + ";" + item.phone);//出租车驾驶员写入Redis
                    cSRedisClient5.Set(item.permit_number, item.id_card + ";" + item.permit_number + ";" + item.name + ";" + item.head_url + ";" + item.phone);//出租车驾驶员写入Redis
                    string insertSql = $@"insert into qskjrecord.B_TaxiDriverZT{dtStr}(id_card,work_numbers,name,dep,permit_number,sex,birthday,head_url,first_get_time,phone)
                                        values('{item.id_card}','{item.work_numbers}','{item.name}','{item.dep}','{item.permit_number}','{item.sex}','{item.birthday}','{item.head_url}','{item.first_get_time}','{item.phone}')";
                    MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, insertSql);
                }
                //大巴数据
                //ZtDataObj<ZtBusDriverData> objBus = JsonConvert.DeserializeObject<ZtDataObj<ZtBusDriverData>>(str);
                foreach (var item in obj.data.dataArray)
                {
                    string insertSql = $@"insert into qskjrecord.B_BusDriverZT{dtStr}(birthday,work_numbers,head_url,permit_number,sex,first_get_time,id_card,name,dep,phone)
                                        values('{item.birthday}','{item.work_numbers}','{item.head_url}','{item.permit_number}','{item.sex}','{item.first_get_time}','{item.id_card}','{item.name}','{item.dep}','{item.phone}')";
                    MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, insertSql);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("读取出租车驾驶员信息异常" + e.Message);
            }
        }
        /// <summary>
        /// 中台大巴车《租赁数据》基础数据
        /// </summary>
        public static void ZtBusLeaseRecordData()
        {
            CSRedisClient? cSRedisClient5 = null;
            string? token = string.Empty;
            try
            {
                if (cSRedisClient5 == null)
                {
                    cSRedisClient5 = RedisHelp.GetInstance5();
                }
                //string dtStrPre = DateTime.Now.AddDays(-5).ToString("yyyyMMdd");
                //string sqlPre = $@"drop table if exists qskjrecord.B_BusLeaseRecordZT{dtStrPre}";
                //MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sqlPre);
                string dtStr = DateTime.Now.ToString("yyyyMMdd");
                if (DateTime.Now.Hour < 7)
                {
                    string exists = $@"SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'qskjrecord' AND TABLE_NAME = 'B_BusLeaseRecordZT{dtStr}';";
                    object resExi = MySqlHelper.ExecuteScalar(CommandType.Text, exists);
                    if (resExi == null || resExi == DBNull.Value)
                    {
                        string sql = $@"create table IF NOT EXISTS qskjrecord.B_BusLeaseRecordZT{dtStr}
                        (
                           id                   bigint not null auto_increment,
                           name_hudi              varchar(50),
                           contacts_hudi         varchar(50),
                           belonging_fleet_hudi                 varchar(50), 
                           file_number_hudi        varchar(50),
                           running_route_hudi                  varchar(50),
                           drivers_license_number1_hudi             varchar(50), 
                           id_hudi             varchar(50),  
                           office_phone_number_hudi       varchar(50),  
                           fleet_hudi       varchar(50),  
                           mobile_phone_number_hudi       varchar(50),  
                           time_3_hudi       varchar(50),   
                           time_2_hudi       varchar(50),  
                           time_3__s_hudi       varchar(50),   
                           date_of_birth_hudi       varchar(50),  
                           departure_hudi       varchar(50),  
                           time_1__s_hudi       varchar(50),  
                           department_hudi       varchar(50),  
                           work_permit_number_hudi       varchar(50),  
                           sys_hudi       varchar(50),  
                           driver_1_hudi       varchar(50),  
                           date_1_hudi       varchar(50),  
                           state_hudi       varchar(50),  
                           age_hudi       varchar(50),  
                           remarks_hudi       varchar(50),  
                           driver_classification_hudi       varchar(50),  
                           license_plate_number_hudi       varchar(50),  
                           destination_hudi       varchar(50),  
                           gender_hudi       varchar(50),  
                           residential_telephone_hudi       varchar(50),   
                           driver_hudi       varchar(50),  
                           endtime_hudi       varchar(50),  
                           date_2_hudi       varchar(50),  
                           isview_hudi       varchar(50),  
                           operations_squadron_hudi       varchar(50),  
                           car_owners_hudi       varchar(50),  
                           statistics_date       varchar(50),  
                           drivers_registration_hudi       varchar(50),  
                           driver_3_hudi       varchar(50),  
                           registration_date_hudi       varchar(50),  
                           picture_hudi       varchar(50),  
                           line_hudi       varchar(50),  
                           driver_2_hudi       varchar(50),  
                           drivers_contact_information_hudi       varchar(50),  
                           isbmp_hudi       varchar(50),   
                           tenant_hudi       varchar(50),  
                           drivers_license_number_hudi       varchar(50),  
                           time_2__s_hudi       varchar(50),  
                           time_1_hudi       varchar(50),  
                           note_100_hudi       varchar(50),  
                           issend_hudi       varchar(50),   
                           ifimage_hudi       varchar(50),  
                           stroke_hudi       varchar(300),  
                           date_hudi       varchar(50),  
                           date_3_hudi       varchar(50),  
                           id_number_hudi       varchar(50),  
                           isup_hudi       varchar(50),  
                           starttime_hudi       varchar(50),   
                           primary key (id)
                        );";
                        MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sql);
                    }
                }

                string sqlCount = $@"select count(*) from qskjrecord.B_BusLeaseRecordZT{dtStr}";
                if (Convert.ToInt32(MySqlHelper.ExecuteScalar(CommandType.Text, sqlCount)) > 0)
                {
                    Console.WriteLine(DateTime.Now + "中台大巴车《租赁数据》基础数据已读取成功");
                    return;
                }
                //读取中台大巴车《租赁数据》基础数据
                if (string.IsNullOrEmpty(token))
                {
                    try
                    {
                        ZtTokenDataInfo response = JsonConvert.DeserializeObject<ZtTokenDataInfo>(HttpHelper.GetZtToken().Result);
                        if (response == null)
                        {
                            Console.WriteLine("获取token失败response为空");
                            return;
                        }
                        if (string.IsNullOrEmpty(response.data))
                        {
                            Console.WriteLine("获取token失败response.data为空");
                            return;
                        }
                        token = response.data;

                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("获取token异常：" + e);
                    }
                }
                var str = HttpHelper.GetZtBusLeaseRecord(token).Result;
                ZtDataObj<ZtDataBusLeaseRecord> obj = JsonConvert.DeserializeObject<ZtDataObj<ZtDataBusLeaseRecord>>(str);
                if (obj == null || obj.data == null || string.IsNullOrEmpty(obj.data.total) || obj.data.total == "0")
                {
                    Console.WriteLine(DateTime.Now + "读取中台大巴车《租赁数据》基础数据" + str);
                    string dtStr1 = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
                    string insertSql1 = $@"insert into qskjrecord.B_BusLeaseRecordZT{dtStr}(
                                        name_hudi,
                                        belonging_fleet_hudi,
                                        file_number_hudi,
                                        id_hudi,
                                        fleet_hudi,
                                        mobile_phone_number_hudi,
                                        time_2_hudi,
                                        date_of_birth_hudi,
                                        departure_hudi,
                                        department_hudi,
                                        sys_hudi,
                                        date_1_hudi,
                                        state_hudi,
                                        age_hudi,
                                        license_plate_number_hudi,
                                        destination_hudi,
                                        gender_hudi,
                                        residential_telephone_hudi,
                                        driver_hudi,
                                        date_2_hudi,
                                        car_owners_hudi,
                                        statistics_date,
                                        drivers_registration_hudi,
                                        driver_3_hudi,
                                        line_hudi,
                                        driver_2_hudi,
                                        drivers_contact_information_hudi,
                                        drivers_license_number_hudi,
                                        time_1_hudi,
                                        stroke_hudi,
                                        date_hudi,
                                        id_number_hudi)

                                        select name_hudi,
                                        belonging_fleet_hudi,
                                        file_number_hudi,
                                        id_hudi,
                                        fleet_hudi,
                                        mobile_phone_number_hudi,
                                        time_2_hudi,
                                        date_of_birth_hudi,
                                        departure_hudi,
                                        department_hudi,
                                        sys_hudi,
                                        date_1_hudi,
                                        state_hudi,
                                        age_hudi,
                                        license_plate_number_hudi,
                                        destination_hudi,
                                        gender_hudi,
                                        residential_telephone_hudi,
                                        driver_hudi,
                                        date_2_hudi,
                                        car_owners_hudi,
                                        statistics_date,
                                        drivers_registration_hudi,
                                        driver_3_hudi,
                                        line_hudi,
                                        driver_2_hudi,
                                        drivers_contact_information_hudi,
                                        drivers_license_number_hudi,
                                        time_1_hudi,
                                        stroke_hudi,
                                        date_hudi,
                                        id_number_hudi from  qskjrecord.B_BusLeaseRecordZT{dtStr1}";
                    MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, insertSql1);
                }
                foreach (var item in obj.data.dataArray)
                {
                    string insertSql = $@"insert into qskjrecord.B_BusLeaseRecordZT{dtStr}(
                                        name_hudi,
                                        belonging_fleet_hudi,
                                        file_number_hudi,
                                        id_hudi,
                                        fleet_hudi,
                                        mobile_phone_number_hudi,
                                        time_2_hudi,
                                        date_of_birth_hudi,
                                        departure_hudi,
                                        department_hudi,
                                        sys_hudi,
                                        date_1_hudi,
                                        state_hudi,
                                        age_hudi,
                                        license_plate_number_hudi,
                                        destination_hudi,
                                        gender_hudi,
                                        residential_telephone_hudi,
                                        driver_hudi,
                                        date_2_hudi,
                                        car_owners_hudi,
                                        statistics_date,
                                        drivers_registration_hudi,
                                        driver_3_hudi,
                                        line_hudi,
                                        driver_2_hudi,
                                        drivers_contact_information_hudi,
                                        drivers_license_number_hudi,
                                        time_1_hudi,
                                        stroke_hudi,
                                        date_hudi,
                                        id_number_hudi)
                                        values('{item.name_hudi}','{item.belonging_fleet_hudi}','{item.file_number_hudi}','{item.id_hudi}','{item.fleet_hudi}','{item.mobile_phone_number_hudi}','{item.time_2_hudi}','{item.date_of_birth_hudi}','{item.departure_hudi}',
                                        '{item.department_hudi}','{item.sys_hudi}','{item.date_1_hudi}','{item.state_hudi}','{item.age_hudi}','{item.license_plate_number_hudi}','{item.destination_hudi}','{item.gender_hudi}','{item.residential_telephone_hudi}','{item.driver_hudi}','{item.date_2_hudi}','{item.car_owners_hudi}','{item.statistics_date}',
                                        '{item.drivers_registration_hudi}','{item.driver_3_hudi}','{item.line_hudi}','{item.driver_2_hudi}','{item.drivers_contact_information_hudi}','{item.drivers_license_number_hudi}','{item.time_1_hudi}','{item.stroke_hudi}','{item.date_hudi}','{item.id_number_hudi}')";
                    MySqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, insertSql);
                    if (!string.IsNullOrWhiteSpace(item.id_number_hudi))
                    {
                        string dr = cSRedisClient5.Get(item.id_number_hudi);//获取驾驶员信息
                        cSRedisClient5.Set(item.license_plate_number_hudi, dr);//设置车辆驾驶员信息
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("中台大巴车《租赁数据》基础数据异常" + e.Message);
            }
        }
        /// <summary>
        /// 角色车辆数据
        /// </summary>
        public static void RoleVehicleData()
        {
            CSRedisClient? cSRedisClient = null, cSRedisClient6 = null;
            string? dtStr = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"), str = DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
            try
            {
                if (cSRedisClient6 == null)
                {
                    cSRedisClient6 = RedisHelp.GetInstance6();
                }
                if (cSRedisClient == null)
                {
                    cSRedisClient = RedisHelp.GetInstance();
                }
                List<int> roles = new List<int>();
                #region 查询角色
                {
                    string sqlRole = $@"select id from qskj.S_Role;";
                    DataTable dtRole = MySqlHelper.GetDataTable(CommandType.Text, sqlRole);
                    foreach (DataRow role in dtRole.Rows)
                    {
                        roles.Add(Convert.ToInt32(role["id"]));
                    }
                }
                #endregion
                #region 查询角色车辆
                List<AlarmVehicleNum> nums = new List<AlarmVehicleNum>();
                {
                    string sqlAla = $@"select busCode,dataNum from qskj.D_AlarmTypeVehicleBc where dayDate>='{DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd HH:mm:ss")}' and typeId=1";
                    DataTable dtAla = MySqlHelper.GetDataTable(CommandType.Text, sqlAla);
                    foreach (DataRow role in dtAla.Rows)
                    {
                        AlarmVehicleNum n = new AlarmVehicleNum();
                        n.busCode = role["busCode"] == DBNull.Value ? "" : Convert.ToString(role["busCode"]);
                        n.dataNum = role["dataNum"] == DBNull.Value ? 0 : Convert.ToInt32(role["dataNum"]);
                        nums.Add(n);
                    }
                }
                foreach (var item in roles)
                {
                    List<RoleVehicleInfo> rvis = new List<RoleVehicleInfo>();
                    string sqlRoleCar = $@"select b.car_assets_name_name,b.dep,b.car_numbers,0 dataNum,e.roleid,a.zl,a.zlterminalkey from qskj.B_Taxi as a
                                join qskjrecord.B_BusZT{str} b on a.license_plate=b.car_numbers
                                join (select roleid,channelid from qskj.R_Role_Channel where roleid={item} and role_type=3 ) e on e.channelid= a.id ;";
                    DataTable dtRoleCar = MySqlHelper.GetDataTable(CommandType.Text, sqlRoleCar);
                    foreach (DataRow role in dtRoleCar.Rows)
                    {
                        RoleVehicleInfo rvi = new RoleVehicleInfo();
                        rvi.company = role["car_assets_name_name"] == DBNull.Value ? "" : role["car_assets_name_name"].ToString();
                        rvi.filiale = role["dep"] == DBNull.Value ? "" : role["dep"].ToString();
                        rvi.licensePlate = role["car_numbers"] == DBNull.Value ? "" : role["car_numbers"].ToString();
                        rvi.dataNum = role["dataNum"] == DBNull.Value ? 0 : Convert.ToInt32(role["dataNum"]);
                        rvi.zl = role["zl"] == DBNull.Value ? 0 : Convert.ToInt32(role["zl"]);
                        rvi.zlterminalkey = role["zlterminalkey"] == DBNull.Value ? "" : role["zlterminalkey"].ToString();
                        rvi.busOrCar = "car";
                        if (rvi.zl == 1)
                        {
                            cSRedisClient.Set($@"zl_{rvi.licensePlate}", rvi.zlterminalkey, new TimeSpan(24, 59, 59));
                            cSRedisClient.Set($@"zl_{rvi.zlterminalkey}", rvi.licensePlate, new TimeSpan(24, 59, 59));
                        }
                        var dn = nums.FirstOrDefault(p => p.busCode == rvi.licensePlate);
                        rvi.dataNum = dn == null ? 0 : dn.dataNum;
                        rvis.Add(rvi);
                    }
                    string sqlRoleBus = $@"select b.car_assets_name_name,b.dep,b.car_numbers,0 dataNum,e.roleid from qskj.B_Bus as a
                                join qskjrecord.B_BusZT{str} b on a.license_plate=b.car_numbers
                                join (select roleid,channelid from qskj.R_Role_Channel where roleid={item} and role_type=2 ) e on e.channelid= a.id;";
                    DataTable dtRoleBus = MySqlHelper.GetDataTable(CommandType.Text, sqlRoleBus);
                    foreach (DataRow role in dtRoleBus.Rows)
                    {
                        RoleVehicleInfo rvi = new RoleVehicleInfo();
                        rvi.company = role["car_assets_name_name"] == DBNull.Value ? "" : role["car_assets_name_name"].ToString();
                        rvi.filiale = role["dep"] == DBNull.Value ? "" : role["dep"].ToString();
                        rvi.licensePlate = role["car_numbers"] == DBNull.Value ? "" : role["car_numbers"].ToString();
                        rvi.busOrCar = "bus";
                        rvi.dataNum = role["dataNum"] == DBNull.Value ? 0 : Convert.ToInt32(role["dataNum"]);
                        var dn = nums.FirstOrDefault(p => p.busCode == rvi.licensePlate);
                        rvi.dataNum = dn == null ? 0 : dn.dataNum;
                        rvis.Add(rvi);
                    }
                    cSRedisClient6.Set($@"roleVeh_{item}", JsonConvert.SerializeObject(rvis), new TimeSpan(23, 59, 00));
                }
                #endregion



            }
            catch (Exception e)
            {
                Console.WriteLine("角色车辆数据缓存到Redis异常" + e.Message);
            }
        }
    }
}
